// custom-tab-bar/index.js
Component({
  data: {
    selected: 0,
    list: [
      {
        pagePath: "/pages/index/index",
        icon: "🏠",
        text: "首页"
      },
      {
        pagePath: "/pages/courses/courses",
        icon: "📚",
        text: "课程"
      },
      {
        pagePath: "/pages/member/member",
        icon: "💎",
        text: "会员"
      },
      {
        pagePath: "/pages/profile/profile",
        icon: "👤",
        text: "我的"
      }
    ]
  },

  attached() {
    console.log('custom-tab-bar attached');
    this.setSelectedTab();
  },

  methods: {
    onTabClick(e) {
      const index = e.currentTarget.dataset.index;
      const item = this.data.list[index];
      
      console.log('点击标签页:', item.text, '索引:', index);
      
      if (this.data.selected === index) {
        console.log('当前页面，不进行切换');
        return;
      }

      wx.switchTab({
        url: item.pagePath,
        success: () => {
          console.log('成功切换到标签页:', item.text);
          this.setData({
            selected: index
          });
        },
        fail: (err) => {
          console.error('标签页切换失败:', err);
          wx.showToast({
            title: '页面切换失败',
            icon: 'none'
          });
        }
      });
    },

    setSelectedTab() {
      const pages = getCurrentPages();
      if (pages.length === 0) return;
      
      const currentPage = pages[pages.length - 1];
      const currentRoute = '/' + currentPage.route;
      
      console.log('当前页面路由:', currentRoute);
      
      const index = this.data.list.findIndex(item => item.pagePath === currentRoute);
      if (index !== -1) {
        console.log('设置选中标签页:', index, this.data.list[index].text);
        this.setData({
          selected: index
        });
      }
    }
  },

  pageLifetimes: {
    show() {
      console.log('custom-tab-bar pageLifetimes show');
      this.setSelectedTab();
    }
  }
});